package zunge.pmp;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import zunge.tools.DbConn;

public class StatUAF {
	public static void main(String[] args){
		statUAF();
	}
	
	static void statUAF(){
		try{
			DbConn connIn = new DbConn("127.0.0.1", "pmp","root","sergeypk428571");
			DbConn connOut = new DbConn("127.0.0.1", "pmp","root","sergeypk428571");
			
			
			
			int u_id, a_id, f_id, d_final, d_prev, d_backandforth;
			int rec_acc; // 0: not acc, 1: acc, 2:not available
			long rec_survival; long t_rec_start;
			int d; long t;int rec;
			
			PreparedStatement ps = connOut.getPreparedStatement("insert into tmp_stat_uaf "
					+ "(u_id, a_id, f_id, d_final, d_prev, d_backandforth, rec_acc, rec_survival) values "
					+ "(?, ?, ?, ?, ?, ?, ?, ?)");
			
			ResultSet rs = connIn.executeQueryInStream("select u_id, a_id, f_id, record from tmp_uaf");
			while(rs.next()){

				u_id = rs.getInt(1);
				a_id = rs.getInt(2);
				f_id = rs.getInt(3);
				String txt = rs.getString(4);
				
				//Scan Log
				String[] records = txt.split(",");

				
				d_final = -1;
				d_prev = -1;
				d_backandforth = 0;
				rec_acc = -1;
				rec_survival = -1;
				t_rec_start = -1;
				
				for(String record:records){
					String[] ffrags = record.split(":");
					d = Integer.parseInt(ffrags[0]); // 1=allow, 0=protect
					t = Long.parseLong(ffrags[1]);
					rec = Integer.parseInt(ffrags[2]); // 1=rec, 0=self, -1=not available
					
					//Check backandforth & update prev
					if(d != d_final){
						if(d == d_prev){ d_backandforth = 1; }
						d_prev = d_final;
						d_final = d;
						
						//Check rec
						switch(rec){ // always remember the latest settings
						case 1://acc
							if(rec_acc!=1){
								rec_survival = -1; t_rec_start = t;
							}
							rec_acc = 1; 
							break;
						case 0://rej
							if(rec_acc == 1){
								if(t_rec_start == -1){
									rec_survival = 0;
								} else{
									rec_survival = t - t_rec_start;
								}
							}
							rec_acc = 0;
							t_rec_start = -1;
							break;
						case 2://not available
							rec_acc = -1;
							rec_survival = -1;
							t_rec_start = -1;
							break;
						}
					}else{
						if(rec == 1){//decision not changed, but became same as recommendation
							rec_acc = 1;
							rec_survival = -1;
							t_rec_start = t;
						}
					}
					
				}
				
				//Write to db
				ps.setInt(1, u_id);
				ps.setInt(2, a_id);
				ps.setInt(3, f_id);
				ps.setInt(4, d_final);
				ps.setInt(5, d_prev);
				ps.setInt(6, d_backandforth);
				ps.setInt(7, rec_acc);
				ps.setLong(8, rec_survival);
				connOut.executeUpdate(ps);
			}
			rs.close();
			
			
			connIn.close();
			connOut.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
